package com.lianyu.wangyiyun.service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.audiofx.Visualizer;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

import androidx.core.app.NotificationCompat;

import com.lianyu.wangyiyun.R;
import com.lianyu.wangyiyun.activity.MainActivity;

import java.io.IOException;

/**
 * @author Chen Yuguang
 */
public class MusicService extends Service {

    private static final String TAG = "MusicService";
    private static final int ONGOING_NOTIFICATION_ID = 1001;
    private static final String CHANNEL_ID = "Music channel";
    private MediaPlayer mMediaPlayer;
    private Visualizer visualizer;
    private final IBinder mBinder = new MusicServiceBinder();
    /**
     * mediaPlayer是否处于初始化状态
     */
    private boolean isInitialized = true;

    public boolean isNotInitialized() {
        return !isInitialized;
    }

    public interface DataCallback {
        /**
         * 画圆时调用
         *
         * @param data 音频信息
         */
        void onCall(byte[] data);

        /**
         * 画波浪时调用
         *
         * @param data 音频信息
         */
        void onWaveCall(byte[] data);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setOnPreparedListener(mp -> {
            mp.start();
            isInitialized = false;
            sendBroadcast(new Intent(MainActivity.ACTION_MUSIC_START));
        });
        //发送播放下一首（考虑模式）的广播
        mMediaPlayer.setOnCompletionListener(mp -> sendBroadcast(new Intent(MainActivity.ACTION_MUSIC_NEXT)));
        mMediaPlayer.setOnErrorListener((mp, what, extra) -> {
            Log.e(TAG, what + " " + extra);
            Toast.makeText(this, "播放失败，将自动播放下一首", Toast.LENGTH_SHORT).show();
            //return false以继续执行onCompletion
            return false;
        });
    }

    @Override
    public void onDestroy() {
        mMediaPlayer.stop();
        mMediaPlayer.release();
        mMediaPlayer = null;
        stopVisualize();
        super.onDestroy();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        isInitialized = true;
        if (mMediaPlayer != null) {
            try {
                mMediaPlayer.reset();
                String url = intent.getStringExtra("url");
                mMediaPlayer.setDataSource(url);
                mMediaPlayer.prepareAsync();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        String title = intent.getStringExtra("title");
        String artist = intent.getStringExtra("artist");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
                    "Music Channel", NotificationManager.IMPORTANCE_HIGH);
            if (mNotificationManager != null) {
                mNotificationManager.createNotificationChannel(channel);
            }
        }
        //设置通知栏点击意图
        Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, 0);
        //获取一个Notification构造器
        NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID);
        Notification notification = builder
                .setContentTitle(title)
                .setContentText(artist)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentIntent(pendingIntent)
                .build();
        startForeground(ONGOING_NOTIFICATION_ID, notification);
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    public class MusicServiceBinder extends Binder {
        public MusicService getService() {
            return MusicService.this;
        }
    }

    /**
     * 停止音频信息获取
     */
    public void stopVisualize() {
        if (visualizer != null) {
            visualizer.setEnabled(false);
            visualizer.release();
            visualizer = null;
        }
    }

    /**
     * 开启音频信息获取
     *
     * @param dataCallback 音频信息获取后的回调接口
     */
    public void startVisualize(DataCallback dataCallback) {
        stopVisualize();
        try {
            visualizer = new Visualizer(mMediaPlayer.getAudioSessionId());
            int captureSize = Visualizer.getCaptureSizeRange()[1];
            int captureRate = Visualizer.getMaxCaptureRate() * 3 / 4;
            visualizer.setCaptureSize(captureSize);
            visualizer.setDataCaptureListener(new Visualizer.OnDataCaptureListener() {
                @Override
                public void onWaveFormDataCapture(Visualizer visualizer, final byte[] waveform, int samplingRate) {
                    if (dataCallback != null) {
                        dataCallback.onWaveCall(waveform);
                    }
                }

                @Override
                public void onFftDataCapture(Visualizer visualizer, final byte[] fft, int samplingRate) {
                    if (dataCallback != null) {
                        dataCallback.onCall(fft);
                    }
                }
            }, captureRate, true, true);
            visualizer.setScalingMode(Visualizer.SCALING_MODE_NORMALIZED);
            visualizer.setEnabled(true);
        } catch (Exception e) {
            Log.e(TAG, "请检查录音权限");
        }
    }

    /**
     * 暂停音乐
     */
    public void pause() {
        if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
            mMediaPlayer.pause();
        }
    }

    /**
     * 播放音乐
     */
    public void play() {
        if (mMediaPlayer != null) {
            mMediaPlayer.start();
        }
    }

    /**
     * 获取音乐总时间
     *
     * @return int 音乐总时间
     */
    public int getDuration() {
        int duration = 0;
        if (mMediaPlayer != null) {
            duration = mMediaPlayer.getDuration();
        }
        return duration;
    }

    /**
     * 获取音乐当前时间
     *
     * @return int 音乐当前时间
     */
    public int getCurrentPosition() {
        int position = 0;
        if (mMediaPlayer != null) {
            position = mMediaPlayer.getCurrentPosition();
        }
        return position;
    }

    /**
     * 音乐是否在播放
     *
     * @return boolean 音乐是否在播放
     */
    public boolean isPlaying() {
        if (mMediaPlayer != null) {
            return mMediaPlayer.isPlaying();
        }
        return false;
    }

    /**
     * 音乐是否循环播放
     *
     * @return boolean 音乐是否循环播放
     */
    public boolean isLooping() {
        if (mMediaPlayer != null) {
            return mMediaPlayer.isLooping();
        }
        return false;
    }

    /**
     * 设置音乐是否循环播放
     */
    public void setLooping(boolean isLooping) {
        if (mMediaPlayer != null) {
            mMediaPlayer.setLooping(isLooping);
        }
    }

    /**
     * 调节播放进度
     *
     * @param position 要跳转的时间
     */
    public void seekTo(int position) {
        if (mMediaPlayer != null) {
            mMediaPlayer.seekTo(position);
        }
    }

}
